package com.example.demo.verify;/**
 * Created by kete on 2019-04-03.
 */

import com.recognition.software.jdeskew.ImageDeskew;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.util.ImageHelper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 作者：kete
 * 创建时间：2019-04-03 10:25
 * 功能描述：
 * 版本：
 */
public class VerificationCode {


    /**
     * 配置文件
     */
    private static String config_path = "src/main/resources";

    private static String tess_data_path = "src/main/resources/tessdata";


    public static String testDoOCR(String filePath) throws Exception {

        File imageFile = new File(filePath);

        ITesseract instance = new Tesseract();
        //set language
        instance.setDatapath(tess_data_path);
        instance.setLanguage("eng");
        String result = instance.doOCR(imageFile);

        return  result;
    }


    /**
     * 调整倾斜度的阈值
     */
    private static double deskew_threshold = 0.05d;

    /**
     * 提取验证码图片中的文字
     *
     * @param img_path
     * @param lang
     * @param clear
     * @return
     */
    public static String extract(String img_path, String lang, boolean clear) throws Exception {
        // 图片文件
        File img = new File(img_path);

        if (clear) {
            // 将去除干扰后的图片保存在同级目录下的ext目录下
            String ext_path = img.getParentFile().getPath() + "/ext";

            // 去除干扰
            CleanImage.cleanLinesInImage(img, ext_path);

            // 处理后的图片
            img = new File(ext_path, img.getName());
        }

        // 设置语言库
        ITesseract instance = new Tesseract();

        instance.setDatapath(tess_data_path);
        // chi_sim表示中文简体
        // eng表示英文
        instance.setLanguage(lang);

        BufferedImage buffer_img = ImageIO.read(img);
        ImageDeskew img_deskew = new ImageDeskew(buffer_img);
        double img_skew_angle = img_deskew.getSkewAngle();
        if ((img_skew_angle > deskew_threshold || img_skew_angle < -(deskew_threshold))) {
            buffer_img = ImageHelper.rotateImage(buffer_img, -img_skew_angle);
        }

        String result = instance.doOCR(buffer_img);

        return result;
    }

    public static void main(String[] args) {

        try {
            String result = VerificationCode.testDoOCR("D:\\temp\\image\\test.jpeg");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
